var that;
class Tab {
  constructor(id) {
    that = this;
    // 获取元素
    this.my = document.querySelector(id);
    this.add = this.my.querySelector(".tabadd");
    this.ul = this.my.querySelector(".fisrstnav ul");
    this.tabscon = this.my.querySelector(".tabscon");
    this.init();
  }
  // 初始化
  init() {
    this.updataNode();
    this.add.onclick = this.addTab;
    for (var i = 0; i < this.lis.length; i++) {
      this.lis[i].index = i;
      this.lis[i].onclick = this.ToggleTab;
      this.guanbi[i].onclick = this.removeTab;
      this.spans[i].ondblclick = this.eidTab;
      this.section[i].ondblclick = this.eidTab;
    }
  }
  updataNode() {
    this.lis = this.my.querySelectorAll("li");
    this.section = this.my.querySelectorAll("section");
    this.guanbi = this.my.querySelectorAll(".icon-guanbi");
    this.spans = this.my.querySelectorAll(".fisrstnav li span:first-child");
  }
  // 切换功能模块
  ToggleTab() {
    that.clear();
    this.className = "liactive";
    that.section[this.index].className = "conactive";
  }
  clear() {
    for (var i = 0; i < this.lis.length; i++) {
      this.lis[i].className = "";
      this.section[i].className = "";
    }
  }
  // 添加功能模块
  addTab() {
    that.clear();
    var random = Math.random();
    var li =
      '<li class="liactive"><span>测试</span><span class="iconfont icon-guanbi"></span></li>';
    var section = '<section class="conactive">测试' + random + "</section>";
    that.ul.insertAdjacentHTML("beforeend", li);
    that.tabscon.insertAdjacentHTML("beforeend", section);
    that.init();
  }
  // 删除功能模块
  removeTab(e) {
    e.stopPropagation();
    var index = this.parentNode.index;
    // this.parentNode.remove();
    that.lis[index].remove();
    that.section[index].remove();
    that.init();
    if (this.parentNode.className === "liactive") {
      index--;
      if (index === -1) index++;
      that.lis[index] && that.lis[index].click();
    }
  }
  // 修改功能模块
  eidTab() {
    // alert('双击了')
    var sta = this.innerHTML;
    this.innerHTML = `<input type='text' value="${sta}"/>`;
    var input = this.children[0];
    input.select();
    input.onblur = function () {
      this.parentNode.innerHTML = this.value;
    };
    input.onkeyup = function (e) {
      if (e.keyCode === 13) return this.blur();
    };
    input.ondblclick = function (e) {
      e.stopPropagation();
    };
  }
}
new Tab("#tab");
